import {Divider, Icon, Popconfirm, Table, Tag, Tooltip} from 'antd'
import React, {Component} from 'react'
import moment from 'moment'
import PreviewModal from './preview-modal'
import {FormattedMessage} from 'react-intl'
import {withRouter} from 'react-router-dom'


class QuizzesTable extends Component {
  state = {
    visible: false,
    quiz: {}
  }

  previewPage = quiz => {
    this.setState({
      visible: true,
      quiz
    })
  }

  editQuiz = quiz => {
    this.props.history.push(`/surveyQuizzes/${quiz.id}/editor`)
  }

  render() {
    const columns = [{
      title: <FormattedMessage id='题目ID'/>,
      dataIndex: 'id',
      sorter: (a, b) => a.id - b.id
    }, {
      title: <FormattedMessage id='描述'/>,
      dataIndex: 'description',
      className: 'description-style'
    }, {
      title: <FormattedMessage id='标签'/>,
      dataIndex: 'tags',
      sorter: (a, b) => a.tags.length - b.tags.length,
      render: text => (text || []).map(tag => <Tag key={tag.id}>{tag.name}</Tag>)
    }, {
      title: <FormattedMessage id='创建时间'/>,
      dataIndex: 'createTime',
      render: (text) => <small>{moment(text).format('YYYY-MM-DD')}</small>
    }, {
      title: <FormattedMessage id='创建者'/>,
      dataIndex: 'maker',
      sorter: (a, b) => a.maker.length - b.maker.length
    }, {
      title: <FormattedMessage id='操作'/>,
      key: 'action',
      render: (text, record) => (
        <span>
          <Tooltip placement='top' title='预览' overlay='preview'>
            <Icon type='eye' className='icon-style' onClick={() => this.previewPage(record)}/>
          </Tooltip>
          <Divider type='vertical'/>

          <Tooltip placement='top' title='编辑' overlay='edit'>
            <Icon type='edit' className='icon-style' onClick={() => this.editQuiz(record)}/>
          </Tooltip>
          <Divider type='vertical'/>

          <Popconfirm title={<FormattedMessage id='确定删除吗?'/>}
                      onConfirm={() => this.props.onDeleteQuiz(record.id)}
                      okText={<FormattedMessage id='确定'/>} cancelText={<FormattedMessage id='取消'/>}>

            <Icon type='delete' className='icon-style'/>
          </Popconfirm>
        </span>
      )
    }]

    const {visible, quiz} = this.state
    const {dataSource, pagination} = this.props

    return (<div className={'table-style'}>
      <Table rowKey={record => record.id}
             columns={columns}
             dataSource={dataSource}
             pagination={pagination}
             bordered
             className='table-center'/>
      {quiz.id
        ? <PreviewModal visible={visible}
                        quiz={quiz}
                        closeModal={() => this.setState({visible: false, quiz: {}})}
        />
        : ''}
    </div>)
  }
}

export default withRouter(QuizzesTable)
